package com.zretc.baiDuFace;
import com.zretc.util.HttpUtil;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import com.zretc.util.Base64Util;
import com.zretc.util.GsonUtils;
public class Facecompare {
	
	public static String faceMatch(String uri1,String uri2) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        
        try {
        	
        	 //Base64转化第一张图片
            String Base64 = changeBase64(uri1);
            
            //Base64转化第二张图片
            String Base641 = changeBase64(uri2);        	
List<Map<String, String>> maps=new ArrayList<Map<String,String>>();
        	
        	
        	Map<String, String> map1 = new HashMap<>();
            map1.put("image",Base64);
            map1.put("image_type", "BASE64");
            map1.put("face_type", "LIVE");
            map1.put("quality_control", "LOW");
            map1.put("liveness_control", "LOW");
            
            
            Map<String, String> map2 = new HashMap<>();
            map2.put("image",Base641);
            map2.put("image_type", "BASE64");
            map2.put("face_type", "IDCARD");
            map2.put("quality_control", "LOW");
            map2.put("liveness_control", "LOW");
            System.out.println(map1);
            maps.add(map1);
            maps.add(map2);
            String param = GsonUtils.toJson(maps);
            

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.810201ae6dcaa18b5376db6258eb9e42.2592000.1597653190.282335-21458214";

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
    	String uri1="E:/20200405/test/me.jpg";
    	String uri2="E:/20200405/test/cf.jpg";
        faceMatch(uri1, uri2);
    }
    
    
    //提方法转Base64图片
    private static  String changeBase64(String url) {
    	
    	 File image = new File(url);
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         String Base64 = null;
         try {
 			BufferedImage img = ImageIO.read(image);
 			ImageIO.write(img, "jpg", out);
 			byte[]bytes = out.toByteArray();
 			Base64=Base64Util.encode(bytes);
 		} catch (IOException e1) {
 			e1.printStackTrace();
 		}
		return Base64;
	}
}
